#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import shutil
sys.path.append('../')

import click
import regex

from utils import tp_logging
from utils import tp_exceptions
from utils import tp_config

logger = tp_logging.get_logger('lyrics_sync')

import lyrics_parser

LRC_DIR = tp_config.get_lrc_dir()
lrc = lyrics_parser.LyricsParser()


class LyricsSync(object):

    def __init__(self, title, artist, length):
        self.song = dict()
        self.song['title'] = title
        self.song['artist'] = artist
        self.song['length'] = length
        self.lrc_file_path = None

    def create_lrc_file(self, replace_lrc=False):
        """Creates a new .lrc.

        A .lrc is generated based on the template found in the assets dir and
        lyrics text is added to it.

        Args:
            replace_lrc (bool): If true, an existing .lrc is recreated without
                synced lines.
        Returns:
            bool: An indicaton of whether a new .lrc file was created with the
            corresponding lyrics.
        """

        remove_special_chars = lambda x: regex.sub('[^a-z-A-Z-0-9- ]', '!', x)

        artist_inline = ', '.join(self.song['artist'])
        artist_no_special = remove_special_chars(artist_inline)
        title_no_special = remove_special_chars(self.song['title'])

        lrc_file_name = '{} - {}.lrc'.format(
            artist_no_special, title_no_special)

        self.lrc_file_path = os.path.join(LRC_DIR, lrc_file_name)

        if not os.path.isfile(self.lrc_file_path) or replace_lrc is True:
            logger.info('New .lrc file created for %s', self.song['title'])
            shutil.copyfile('assets/lrc.lrc', self.lrc_file_path)
            lrc_lines = lrc.get_lyrics(
                song=self.song['title'], artist=artist_inline)

            with open(self.lrc_file_path, 'a') as open_lrc:
                for line in lrc_lines:
                    timing_line = '[mm:ss.xx]{}'.format(line)
                    print(timing_line, file=open_lrc)

            return True

        else:
            logger.info('Lyrics already avaliable at %s', self.lrc_file_path)

        return False

